﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Linq;

using Tools.Json;

using SY.WebSite.Entity;
using SY.WebSite.BLL;

namespace SY.WebSite.Web.Handler
{
    public class AuctionHandler : InternalWebHandler, IHttpHandler
    {
        public new void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);

            switch (Action)
            {
                case "list":
                    List();
                    break;
                case "bid":
                    Bid();
                    break;
                case "queryBid":
                    QueryBid();
                    break;
                case "cancelBid":
                    CancelBid();
                    break;
                case "history":
                    History();
                    break;
                case "my":
                    My();
                    break;
            }

            context.Response.End();
        }

        public void My()
        {
            Response.Write(new JsonTransfer().Add("list", BizAuctionItem.GetMyListByUserId(CurrentUser.UserId)));
        }

        public void History() {
            JsonTransfer jt = new JsonTransfer();
            IEnumerable<Auction> history = BizAuction.GetHistoryList();
            int pageIndex = RequestIntParam("pageIndex");
            int pageSize = RequestIntParam("pageSize", 20);

            jt.Add("count", history != null ? history.Count() : 0);

            if (history != null && history.Count() > 0)
                history = history.Skip(pageSize * pageIndex).Take(pageSize);

            jt.Add("list", history);
            Response.Write(jt);
        }

        public void CancelBid()
        {
            int auctionId = Tools.Web.Request.GetFormInt("auctionId", 0);
            int auctionItemId = Tools.Web.Request.GetFormInt("auctionItemId", 0);

            List<AuctionItem> list = GetCurrentAuctionItem();
            if (list == null || list.Count <= 0)
                BreakResponse();

            AuctionItem auctionItem = list.FirstOrDefault(l => l.AuctionId == auctionId && l.Id == auctionItemId);
            if (auctionItem == null)
                BreakResponse();

            if (auctionItem.Bidder == CurrentUser.UserId)
                BreakResponse("该物品您为最高竞拍者，不能撤销竞拍");

            AuctionItemBid entry = new AuctionItemBid { 
                UserId = CurrentUser.UserId,
                AuctionItemId = auctionItemId,
                AuctionId = auctionId
            };
            int result = BizAuctionItemBid.Delete(entry);
            switch (result) { 
                case -1:
                    BreakResponse();
                    break;
                case -2:
                    BreakResponse("该物品您为最高竞拍者，不能撤销竞拍");
                    break;
                default:
                    Response.Write(new JsonTransfer().Add("list", BizAuctionItemBid.GetListByAuctionItemId(auctionItemId)));
                    break;
            }
        }

        public void QueryBid() {
            int auctionId = Tools.Web.Request.GetFormInt("auctionId", 0);
            int auctionItemId = Tools.Web.Request.GetFormInt("auctionItemId", 0);

            //List<AuctionItem> list = GetCurrentAuctionItem();
            //if (list == null || list.Count <= 0 || !list.Exists(l => l.AuctionId == auctionId && l.Id == auctionItemId))
            //    BreakResponse();

            Response.Write(new JsonTransfer().Add("list", BizAuctionItemBid.GetListByAuctionItemId(auctionItemId)));
        }

        public void Bid()
        {
            int auctionId = Tools.Web.Request.GetFormInt("auctionId", 0);
            int auctionItemId = Tools.Web.Request.GetFormInt("auctionItemId", 0);
            int amount = Tools.Web.Request.GetFormInt("amount", 0);

            if (auctionItemId <= 0 || auctionId <= 0)
                BreakResponse();

            if (amount <= 0)
                BreakResponse("竞拍素币必须大于0");

            List<AuctionItem> list = GetCurrentAuctionItem();
            if (list == null || list.Count <= 0 || !list.Exists(l => l.AuctionId == auctionId && l.Id == auctionItemId))
                BreakResponse();

            Integration integration = BizIntegration.GetByKey(CurrentUser.UserId);
            if (integration.Available < amount)
                BreakResponse("竞拍素币不能超过自己的可用素币");

            AuctionItemBid bid = new AuctionItemBid
                                     {
                                         AuctionId = auctionId,
                                         AuctionItemId = auctionItemId,
                                         Amount = amount,
                                         UserId = CurrentUser.UserId,
                                         UserName = CurrentUser.UserName
                                     };
            int result = BizAuctionItemBid.Add(bid);
            switch (result)
            {
                //0+正常 -1竞拍不存在 -2信息错误 -3已有更高投注 -4素币不足
                case -1:
                case -2:
                case -4:
                    BreakResponse();
                    break;
                case -3:
                    BreakResponse("已有更高投注，请刷新后重试");
                    break;
                case -5:
                    BreakResponse("同场竞拍中您已竞拍别的物品");
                    break;
                default:
                    Response.Write(new JsonTransfer().Add("list", BizAuctionItemBid.GetListByAuctionItemId(auctionItemId)));
                    break;
            }
        }

        public void List()
        {
            JsonTransfer jt = new JsonTransfer();
            IEnumerable<Auction> list = BizAuction.GetProcessingList();
            Auction current = null;
            if (list != null && list.Count() > 0)
                current = list.FirstOrDefault();

            List<AuctionItem> itemList = GetCurrentAuctionItem();
            jt.Add("list", itemList);
            jt.Add("lastSecond", itemList.Count > 0 && current != null ? (current.EndTime - DateTime.Now).TotalSeconds : 0);
            Response.Write(jt);
        }

        private static List<AuctionItem> GetCurrentAuctionItem()
        {
            List<AuctionItem> items = new List<AuctionItem>();

            IEnumerable<Auction> list = BizAuction.GetProcessingList();
            if (list != null && list.Count() > 0)
            {
                foreach (var auction in list)
                {
                    items.AddRange(BizAuctionItem.GetListByAuctionId(auction.Id));
                }
            }
            return items;
        }
    }
}